自旋锁:pthread

您所在的位置:网站首页 pthread_mutex_t lock 自旋锁:pthread

自旋锁:pthread

2024-03-24 04:27| 来源: 网络整理| 查看: 265

Table of Contents

pthread提供的锁

互斥锁

自旋锁

pthreadtypes.h    nptl\sysdeps\unix\sysv\linux\i386\bits    4477    5/28/2007    

读写锁

条件变量

pthread提供的锁

POSIX threads(简称Pthreads)是在多核平台上进行并行编程的一套常用的API。

线程同步(Thread Synchronization)是并行编程中非常重要的通讯手段,其中最典型的应用就是用Pthreads提供的锁机制(lock)来对多个线程之间共 享的临界区(Critical Section)进行保护(另一种常用的同步机制是barrier)。

Pthreads提供了多种锁机制:https://blog.csdn.net/sunmenggmail/article/details/8105279

(1) Mutex(互斥量):pthread_mutex_***(2) Spin lock(自旋锁):pthread_spin_***(3) Condition Variable(条件变量):pthread_con_***(4) Read/Write lock(读写锁):pthread_rwlock_*** 互斥锁

Pthreads提供的Mutex锁操作相关的API主要有:

pthread_mutex_lock (pthread_mutex_t *mutex); pthread_mutex_trylock (pthread_mutex_t *mutex); pthread_mutex_unlock (pthread_mutex_t *mutex); 自旋锁

自旋锁在glibc-2.9中的定义为

pthreadtypes.h    nptl\sysdeps\unix\sysv\linux\i386\bits    4477    5/28/2007     /* POSIX spinlock data type. */ typedef volatile int pthread_spinlock_t;

Pthreads提供的与Spin Lock锁操作相关的API主要有:

pthread_spin_lock (pthread_spinlock_t *lock); pthread_spin_trylock (pthread_spinlock_t *lock); pthread_spin_unlock (pthread_spinlock_t *lock);

从 实现原理上来讲,Mutex属于sleep-waiting类型的锁。例如在一个双核的机器上有两个线程(线程A和线程B),它们分别运行在Core0和 Core1上。假设线程A想要通过pthread_mutex_lock操作去得到一个临界区的锁,而此时这个锁正被线程B所持有,那么线程A就会被阻塞 (blocking),Core0 会在此时进行上下文切换(Context Switch)将线程A置于等待队列中,此时Core0就可以运行其他的任务(例如另一个线程C)而不必进行忙等待。而Spin lock则不然,它属于busy-waiting类型的锁,如果线程A是使用pthread_spin_lock操作去请求锁,那么线程A就会一直在 Core0上进行忙等待并不停的进行锁请求,直到得到这个锁为止。

所以,自旋锁一般用用多核的服务器。

读写锁

https://blog.csdn.net/Rong_Toa/article/details/100051839

条件变量

条件变量:pthread_cond_t

 



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3